package com.serkol.ams.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.ams.bean.*;
import com.serkol.ams.entity.*;
import com.serkol.ams.service.*;
import com.serkol.annotation.IsLogin;
import com.serkol.component.SystemSettingUtils;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.constant.ResultConstant;
import com.serkol.exception.AuthException;
import com.serkol.exception.SerkolProjectException;
import com.serkol.utils.OrderUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import javax.validation.Valid;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("api/users")
public class UsersApiController {


    @Autowired
    private UsersService userService;

    @Autowired
    private UsersAuthenticationService usersAuthenticationService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private AgentRechangeLogService agentRechangeLogService;
    @Autowired
    private UsersInvitationRelationshipService invitationRelationshipService;
    @Autowired
    private SystemSettingUtils systemSettingUtils;


    @Autowired
    private WxMpService wxMpService;


    @Autowired
    private FamousService famousService;

    @IsLogin
    @PostMapping("/wxMiniPhone")
    @ResponseBody
    public Result wxMiniPhone(@RequestBody @Valid WxMiniPhoneConfig wxMiniConfig) throws SerkolProjectException, WxErrorException, AuthException {
//wxMiniPhone
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(wxMiniConfig.getSessionKey(), wxMiniConfig.getEncryptedData(), wxMiniConfig.getIv());
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        System.out.println(phoneNoInfo.getPhoneNumber());
        boolean flag = userService.editPhoneNumber(phoneNumber);
        //    System.out.println(phoneNoInfo.getPurePhoneNumber());
        if (flag) {
            UsersAuthentication info = usersAuthenticationService.getInfo();
            if (info == null) {
                LoginLog loginLog = AuthConstant.getLoginLog();
                info = new UsersAuthentication();
                info.setUserId(loginLog.getUserId());
                info.setWechat(phoneNumber);
            }
            info.setPhone(phoneNumber);
            usersAuthenticationService.saveOrUpdate(info);

            return Result.ok(phoneNumber);
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }

    }

    //

    @IsLogin
    @GetMapping(value = "inviteCode", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] invitation(@RequestParam(value = "inviteUserId", defaultValue = "0") Long inviteUserId) throws WxErrorException {
        //String.valueOf(inviteUserId)
        File file = wxMaService.getQrcodeService().createQrcode("pages/index/user", 300);

        return FileUtil.readBytes(file);

    }


    //getAgentUserFeild
    @IsLogin
    @GetMapping("/findByAgentList")
    public Result findByMiniList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current, @RequestParam(name = "agentId", defaultValue = "0") long agentId,  @RequestParam(name = "userId", defaultValue = "0") long userId) {

        return userService.findByMiniList(pageSize, current, agentId, userId);

    }

    //getAgentUserFeild
    @IsLogin
    @GetMapping("/findByAgentMiniList")
    public Result findByAgentMiniList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "1") int current, @RequestParam(name = "agentId", defaultValue = "0") long agentId
            , @RequestParam(name = "userId", defaultValue = "0") long userId) {

        return userService.findByMiniList(pageSize, current, agentId,userId);

    }

    @IsLogin
    @GetMapping("/currentUser")
    // @Cacheable(value = "HHHHHH", key = "'UsersApiController:findByList'")
    public Result currentUser() {

        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);

        Map<String, Object> one = userService.getCurrentUser();

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @GetMapping("/findByOutId")
    public Result findByOutId(@RequestParam(name = "userId", defaultValue = "0") long userId) {

       Users one = userService.findByUserId(userId);

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @IsLogin
    @GetMapping("/findById")
    public Result findById(@RequestParam(name = "userId", defaultValue = "1") long userId) {

        Map<String, Object> one = userService.findById(userId);

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @GetMapping("/findByOnId")
    public Result findByOnId(@RequestParam(name = "userId", defaultValue = "0") long userId) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        if (loginLog != null && userId == 0) {
            if (loginLog.getParentUserId() != null) {
                if (loginLog.getParentUserId() > 0) {
                    userId = loginLog.getParentUserId();
                }
            }
        }

        Map<String, Object> one = userService.findById(userId);

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current,
                                 @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "userName", defaultValue = "") String userName
            , @RequestParam(name = "authName", defaultValue = "") String authName
            , @RequestParam(name = "id", defaultValue = "0") long id
            , @RequestParam(name = "agentId", defaultValue = "0") long agentId
            , @RequestParam(name = "status", defaultValue = "-5") int status
            , @RequestParam(name = "nickname", defaultValue = "") String nickname
            , @RequestParam(name = "phone", defaultValue = "") String phone) {
        Result result = new Result();
        return userService.findByList(pageSize, current, invite.trim(), userName.trim(), nickname.trim(), phone.trim(), authName.trim(), id, agentId,status);

    }

    @IsLogin
    @GetMapping("/findByPageMiniList")
    public Result findByPageMiniList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current,
                                     @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "userName", defaultValue = "") String userName
            , @RequestParam(name = "nickname", defaultValue = "") String nickname
            , @RequestParam(name = "phone", defaultValue = "") String phone     , @RequestParam(name = "authName", defaultValue = "") String authName
            , @RequestParam(name = "id", defaultValue = "0") long id
            , @RequestParam(name = "agentId", defaultValue = "0") long agentId
            , @RequestParam(name = "status", defaultValue = "-5") int status) {
        Result result = new Result();
        return userService.findByList(pageSize, current, invite, userName, nickname, phone, authName, id, agentId,status);


    }


    //    agentName:"1"
//    invite:"1"
//    name:"1"
//    parentName:"1"
//    phone:"1"
//    wechat:"1"
    @IsLogin
    @GetMapping("/findByPageBackAgentList")
    public Result findByPageBackAgentList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current
            , @RequestParam(name = "agentId", defaultValue = "0") long agentId
            , @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "name", defaultValue = "") String name
            , @RequestParam(name = "parentName", defaultValue = "") String parentName
            , @RequestParam(name = "phone", defaultValue = "") String phone
            , @RequestParam(name = "wechat", defaultValue = "") String wechat
    ) {
//        Map<String, Object> params=new HashMap<>();
//        params.put("agentName",agentName);
//        params.put("invite",invite);
//        params.put("name",name);
//        params.put("parentName",parentName);
//        params.put("phone",phone);
//        params.put("wechat",wechat);


        Result result = new Result();
        return userService.findByPageBackAgentList(pageSize, current, agentId, invite.trim(), name.trim(), parentName.trim(), phone.trim(), wechat.trim());


    }


    //    agentName:"1"
//    invite:"1"
//    name:"1"
//    parentName:"1"
//    phone:"1"
//    wechat:"1"
    @IsLogin
    @GetMapping("/findByPageBackAgentMiniList")
    public Result findByPageBackAgentMiniList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current
            , @RequestParam(name = "agentId", defaultValue = "0") long agentId
            , @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "name", defaultValue = "") String name
            , @RequestParam(name = "parentName", defaultValue = "") String parentName
            , @RequestParam(name = "phone", defaultValue = "") String phone
            , @RequestParam(name = "wechat", defaultValue = "") String wechat
    ) {
//        Map<String, Object> params=new HashMap<>();
//        params.put("agentName",agentName);
//        params.put("invite",invite);
//        params.put("name",name);
//        params.put("parentName",parentName);
//        params.put("phone",phone);
//        params.put("wechat",wechat);


        Result result = new Result();
        return userService.findByPageBackAgentList(pageSize, current, agentId, invite, name, parentName, phone, wechat);

    }

    @IsLogin
    @GetMapping("/findTreeList")
    @Cacheable(cacheNames = "userstree", key = "'findTreeList'+#userId")
    public Result findTreeList(@RequestParam(name = "userId", defaultValue = "0") long userId) {
        Result result = new Result();
        List<Map<String, Object>> list = userService.getBackFindTreeList(0L);

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都要默认值的

        treeNodeConfig.setParentIdKey("parentUserId");
// 最大递归深度
        treeNodeConfig.setDeep(3);
        List<Tree<String>> treeList = TreeUtil.build(list, userId > 0 ? String.valueOf("c1" + userId) : null, treeNodeConfig,
                (treeNode, tree) -> {
                    System.out.println(treeNode.toString());
                    tree.setId("c1" + treeNode.get("id"));
                    if (treeNode.containsKey("parentUserId")) {
                        tree.setParentId("c1" + treeNode.get("parentUserId"));
                    }

                    //     tree.setWeight(treeNode.getPhone());
                    //tree.setName(treeNode.getNickname());
                    //  tree.putExtra("avatar", treeNode.getAvatar());
                    // 扩展属性 ...
                    //  tree.putExtra("extraField", 666);
                    //   tree.putExtra("other", new Object());
                    //   name: string;
                    //    title?: string;
                    //    icon?: string;
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", treeNode.get("name"));
                    map.put("title", treeNode.get("agentName"));
                    map.put("icon", treeNode.get("avatar"));
                    //   tree.putExtra("id",String.valueOf(treeNode.getId()));
                    // tree.putExtra("parentUserId",String.valueOf(treeNode.getParentUserId()));
                    tree.putExtra("value", map);
                    System.out.println(tree.toString());
                });
        result.setStatus(ResultConstant.SUCSESS);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "公司");
        map1.put("title", "系统");
        map1.put("icon", "http://");
        map.put("id", "c1");
        map.put("value", map1);
        map.put("children", treeList);
        result.setData(map);

        return result;
    }

    @IsLogin
    @GetMapping("/findMyTreeList")
    public Result findMyTreeList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "1") int current, @RequestParam(name = "userId", defaultValue = "0") long userId) {
        // System.out.println(pageSize+"------------|||||-----------"+current);
        LoginLog loginLog = AuthConstant.getLoginLog();
        if (userId == 0) {
            userId = loginLog.getUserId();
        }

        return userService.findParentByMiniList(pageSize, current, userId);

    }


    @IsLogin
    @PostMapping("edit")
    public Result edit(@RequestBody UsersInfo usersInfo) {
        System.out.println(usersInfo);
        LoginLog loginLog = AuthConstant.getLoginLog();


        if (userService.isPhoneAndIdValid(usersInfo.getPhone(), usersInfo.getId()) || !userService.isPhoneValid(usersInfo.getPhone())) {
            AgentRechangeLog agentRechangeLog = new AgentRechangeLog();
            Users byUserId = userService.findByUserId(usersInfo.getId());
            agentRechangeLog.setUserId(byUserId.getId());
            agentRechangeLog.setOperatorId(loginLog.getUserId());
            agentRechangeLog.setOldAgentId(byUserId.getAgentId());
            agentRechangeLog.setAgentId(usersInfo.getAgentId());
            agentRechangeLog.setOldParentUserId(byUserId.getParentUserId());
            Users users = new Users();
            users.setId(usersInfo.getId());
            users.setPhone(usersInfo.getPhone());
            users.setUserName(usersInfo.getUserName());
            users.setInvite(usersInfo.getInvite());
            users.setAgentId(usersInfo.getAgentId());
            if (StringUtils.isNotEmpty(usersInfo.getPassword())) {
                MD5 md5 = MD5.create();
                String s = md5.digestHex(usersInfo.getPassword());
                users.setUserPassword(s);
            }

            if (StringUtils.isNotEmpty(usersInfo.getParentUser())) {
                if (userService.isPhoneValid(usersInfo.getParentUser())) {
                    Users byUserPhone = userService.findByUserPhone(usersInfo.getParentUser());
                    users.setParentUserId(byUserPhone.getId());
                    agentRechangeLog.setParentUserId(byUserPhone.getParentUserId());
                } else {
                    return Result.failure();
                }
            }
            boolean b = userService.updateById(users);
            if (b) {
                UsersAuthentication usersAuthentication = new UsersAuthentication();
                usersAuthentication.setUserId(usersInfo.getId());
                usersAuthentication.setName(usersInfo.getName());
                usersAuthentication.setAddress(usersInfo.getAddress());
                usersAuthentication.setBankAddress(usersInfo.getBankAddress());
                usersAuthentication.setBankCard(usersInfo.getBankCard());
                usersAuthentication.setPhone(usersInfo.getPhone());
                usersAuthentication.setWechat(usersInfo.getWechat());
                QueryWrapper<UsersAuthentication> usersAuthenticationQueryWrapper = new QueryWrapper<>();
                usersAuthenticationQueryWrapper.lambda().eq(UsersAuthentication::getUserId, users.getId());
                boolean update = usersAuthenticationService.saveOrUpdate(usersAuthentication, usersAuthenticationQueryWrapper);
                if (update) {
                    if (agentRechangeLog.getAgentId() != agentRechangeLog.getOldAgentId() || agentRechangeLog.getParentUserId() != agentRechangeLog.getOldParentUserId()) {

                        agentRechangeLogService.save(agentRechangeLog);
                    }
                    return Result.ok();
                } else {
                    return Result.failure();
                }
            } else {

                return Result.failure();
            }
        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @PostMapping("editReg")
    public Result editReg(@RequestBody UsersInfo usersInfo) {
        System.out.println(usersInfo);
        LoginLog loginLog = AuthConstant.getLoginLog();
        if (!userService.isPhoneValid(usersInfo.getPhone())) {
            String invalidCode = OrderUtils.getInvalidCode(usersInfo.getId());
            Users users = new Users();

            users.setId(usersInfo.getId());
            users.setPhone(usersInfo.getPhone());
            users.setUserName(usersInfo.getUserName());
            users.setInvite(invalidCode);
            users.setAgentId(usersInfo.getAgentId());
            if (StringUtils.isNotEmpty(usersInfo.getPassword())) {
                MD5 md5 = MD5.create();
                String s = md5.digestHex(usersInfo.getPassword());
                users.setUserPassword(s);
            }


            boolean b = userService.save(users);
            if (b) {
                UsersAuthentication usersAuthentication = new UsersAuthentication();
                usersAuthentication.setUserId(usersInfo.getId());
                usersAuthentication.setName(usersInfo.getName());
                usersAuthentication.setAddress(usersInfo.getAddress());
                usersAuthentication.setBankAddress(usersInfo.getBankAddress());
                usersAuthentication.setBankCard(usersInfo.getBankCard());
                usersAuthentication.setPhone(usersInfo.getPhone());
                usersAuthentication.setWechat(usersInfo.getWechat());
                QueryWrapper<UsersAuthentication> usersAuthenticationQueryWrapper = new QueryWrapper<>();
                usersAuthenticationQueryWrapper.lambda().eq(UsersAuthentication::getUserId, users.getId());
                boolean update = usersAuthenticationService.saveOrUpdate(usersAuthentication, usersAuthenticationQueryWrapper);
                if (update) {
                    AgentRechangeLog agentRechangeLog = new AgentRechangeLog();
                    if (StringUtils.isNotEmpty(usersInfo.getParentUser())) {
                        if (userService.isPhoneValid(usersInfo.getParentUser())) {
                            Users byUserPhone = userService.findByUserPhone(usersInfo.getParentUser());
                            users.setParentUserId(byUserPhone.getId());
                            agentRechangeLog.setParentUserId(byUserPhone.getParentUserId());
                        } else {
                            return Result.failure();
                        }
                    }

                    agentRechangeLog.setUserId(users.getId());
                    agentRechangeLog.setOperatorId(loginLog.getUserId());
                    agentRechangeLog.setOldAgentId(users.getAgentId());
                    agentRechangeLog.setAgentId(usersInfo.getAgentId());
                    agentRechangeLog.setOldParentUserId(users.getParentUserId());
                    if (agentRechangeLog.getAgentId() != agentRechangeLog.getOldAgentId() || agentRechangeLog.getParentUserId() != agentRechangeLog.getOldParentUserId()) {

                        agentRechangeLogService.save(agentRechangeLog);
                    }
                    return Result.ok();
                } else {
                    return Result.failure();
                }
            } else {

                return Result.failure();
            }
        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @PostMapping("editAgentUpdate")
    public Result editAgentUpdate(@RequestBody UsersInfo usersInfo) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        AgentRechangeLog agentRechangeLog = new AgentRechangeLog();
        agentRechangeLog.setOperatorId(loginLog.getUserId());
        agentRechangeLog.setAgentId(usersInfo.getAgentId());
        Users byUserId = userService.findByUserId(usersInfo.getId());
        agentRechangeLog.setUserId(byUserId.getId());
        agentRechangeLog.setParentUserId(byUserId.getParentUserId());
        agentRechangeLog.setOldAgentId(byUserId.getAgentId());
        agentRechangeLog.setOldParentUserId(byUserId.getParentUserId());
        Users users = new Users();
        users.setId(usersInfo.getId());
        users.setAgentId(usersInfo.getAgentId());
        if (usersInfo.getAgentId() != null) {
            if (users.getAgentId() > 1) {
                users.setAgentState(1);
            }
            boolean b = userService.updateById(users);
            if (b) {
                agentRechangeLogService.save(agentRechangeLog);
                return Result.ok();
            } else {
                return Result.failure();
            }
        } else {
            return Result.failure();
        }
    }

    @IsLogin
    @PostMapping("brackUpdate")
    public Result brackUpdate(@RequestBody JSONObject jsonObject) {
        long id = jsonObject.getLongValue("id");
        int type = jsonObject.getIntValue("type");
        int state = jsonObject.getIntValue("state");
        System.out.println("ID:" + id + " Type:" + type + " State:" + state);
        Users users = new Users();
        users.setId(id);

        switch (type) {
            case 1:
                long ordinary = agentService.getOrdinary(0);
                users.setAgentId(ordinary);
                users.setAgentState(0);
                break;
            case 2:
                users.setStatus(state);
                break;
        }
        System.out.println(users);
        if (type > 0) {

            boolean b = userService.updateById(users);
            if (b) {
                return Result.ok();
            } else {
                return Result.failure();
            }
        } else {
            return Result.failure();
        }
    }


    @Transactional
    @PostMapping("/myEdit")
    @ResponseBody
    public Result myEdit(HttpServletRequest request, @RequestBody  UsersAuthentication regesterInfo) throws SerkolProjectException, WxErrorException {
        System.out.println("MYEDIT---------------------------------------------------");
        System.out.println(regesterInfo);
        LoginLog loginLog = AuthConstant.getLoginLog();
        Result result = new Result();
        Users byLogin = userService.findByUserId(loginLog.getUserId());
        List<UsersAuthentication> list1 = new ArrayList<>();
 /*       List<UsersAuthentication> list = usersAuthenticationService.list();
        Iterator<UsersAuthentication> iterator = list.iterator();
        while (iterator.hasNext()) {
            UsersAuthentication next = iterator.next();
            Famous famous = famousService.findByName(next.getName());

            if (famous != null) {
                next.setNameUg(famous.getNameUg());
                list1.add(next);
            }
        }
        usersAuthenticationService.saveOrUpdateBatch(list1);*/

        if (byLogin != null) {

            UsersAuthentication usersAuthentication = usersAuthenticationService.getInfo();
            if(usersAuthentication == null){
                usersAuthentication = new UsersAuthentication();
            }
            usersAuthentication.setWechat(regesterInfo.getWechat());
            if ((regesterInfo.getPhone() != null) && !StringUtils.equals(regesterInfo.getPhone(), byLogin.getPhone())) {
                boolean bb = userService.isPhoneValid(regesterInfo.getPhone());
                if(!bb){
                    usersAuthentication.setPhone(regesterInfo.getPhone());
                    byLogin.setPhone(regesterInfo.getPhone());
                }else{
                    result.setStatus(ResultConstant.FAIL);
                    result.setMsg("手机号已存在");
                    return result;
                }
            }



            if (!StringUtils.equals(usersAuthentication.getName(), regesterInfo.getName())) {
                Famous famous = famousService.findByName(regesterInfo.getName());
                System.out.println(famous);
                usersAuthentication.setName(regesterInfo.getName());
                usersAuthentication.setNameUg(famous.getNameUg());
            }else{
                usersAuthentication.setName(regesterInfo.getName());
            }
            usersAuthentication.setIdcard(regesterInfo.getIdcard());
            usersAuthentication.setAddress(regesterInfo.getAddress());
            usersAuthentication.setUserId(byLogin.getId());

            boolean b = usersAuthenticationService.saveOrUpdate(usersAuthentication);
            if (b) {
                if ((regesterInfo.getPhone() != null) && !StringUtils.equals(regesterInfo.getPhone(), byLogin.getPhone())) {
                    userService.updateById(byLogin);
                }

                result.setStatus(ResultConstant.SUCSESS);
            } else {
                result.setStatus(ResultConstant.FAIL);
            }

        } else {
            result.setStatus(ResultConstant.FAIL);
        }


        //   wxMaService.getUserService().
        return result;
    }


    @IsLogin
    @GetMapping("serachByPhone")
    public Result serachByPhone(@RequestParam(value = "phone", defaultValue = "") String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            Map<String, Object> byUserPhone = userService.findByUserAuthPhone(phone);
            if (byUserPhone != null) {
                return Result.ok(byUserPhone);
            } else {
                return Result.failure(ResultConstant.EMPTIY);
            }

        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @GetMapping("serachMiniByPhone")
    public Result serachMiniByPhone(@RequestParam(value = "phone", defaultValue = "") String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            List<Map<String, Object>> byUserPhone = userService.findMiniByUserAuthPhone(phone);
            if (byUserPhone != null) {
                return Result.ok(byUserPhone);
            } else {
                return Result.failure(ResultConstant.EMPTIY);
            }

        } else {
            return Result.failure();
        }

    }


    @Transactional
    @PostMapping("/regesterMini")
    @ResponseBody
    public Result regesterMini(HttpServletRequest request, @RequestBody UsersRegesterInfo regesterInfo) throws SerkolProjectException, WxErrorException, AuthException {


        System.out.println(regesterInfo);
        Result result = new Result();
        Long agentIdDefault = 1L;
        String agendefaultid = systemSettingUtils.getInfo("agendefaultid");
        System.out.println("llllll:" + agendefaultid);
        if (StringUtils.isNotEmpty(agendefaultid)) {
            agentIdDefault = Long.valueOf(agendefaultid);
        }
        if (StringUtils.isNotEmpty(regesterInfo.getPhone())) {
            boolean bb = userService.isPhoneValid(regesterInfo.getPhone());


            if (bb == false) {

                Users byLogin = new Users();

                Users usersDetail = new Users();
                usersDetail.setAgentId(agentIdDefault);
                usersDetail.setPhone(regesterInfo.getPhone());

                //     usersDetail.setOpenid(openid);
                if (regesterInfo.getParentUserId() != null) {
                    boolean isUser = userService.isUsers(regesterInfo.getParentUserId());
                    if (isUser) {
                        usersDetail.setParentUserId(regesterInfo.getParentUserId());

                    }
                }
                if (StringUtils.isNotEmpty(regesterInfo.getPassword())) {
                    MD5 md5 = MD5.create();
                    String s = md5.digestHex(regesterInfo.getPassword());
                    usersDetail.setUserPassword(s);
                }
                //  usersDetail.setUserPassword(regesterInfo.getPassword());
                usersDetail.setPhone(regesterInfo.getPhone());
                //   usersDetail.setInvite("");


                byLogin = userService.findByLoginAndInsert(usersDetail);
                if (byLogin.getId() > 0) {
                    String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                    byLogin.setInvite(invalidCode);
                    userService.updateById(byLogin);
                    UsersAuthentication usersAuthentication = new UsersAuthentication();
                    usersAuthentication.setWechat(regesterInfo.getWechat());
                    usersAuthentication.setPhone(regesterInfo.getPhone());
                    usersAuthentication.setName(regesterInfo.getName());
                    usersAuthentication.setIdcard(regesterInfo.getIdcard());
                    usersAuthentication.setUserId(byLogin.getId());
                    if (regesterInfo.getParentUserId() != null) {
                        invitationRelationshipService.invalidUsers(byLogin.getId(), regesterInfo.getParentUserId());
                    }
                    boolean b = usersAuthenticationService.saveOrUpdate(usersAuthentication);
                    if (b) {
                        return Result.ok(byLogin);
                    } else {
                        throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
                    }
                } else {
                    throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
                }


            } else {

                throw new AuthException(ResultCode.OK_ACCEPTED);


            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_FOUND);
        }

    }

    @IsLogin
    @GetMapping("/findMyParentList")
    public Result findMyParentList(@RequestParam(name = "userId", defaultValue = "0") long userId) {
        // System.out.println(pageSize+"------------|||||-----------"+current);


        List<Map<String, Object>> list = userService.findMyParentList(userId);
        //   List<Map<String, Object>> list = userService.listMaps(query);
        return Result.ok(list);
    }

   // @IsLogin
    @GetMapping("/findMyBrithList")
    public Result findMyBrithList() {
        // System.out.println(pageSize+"------------|||||-----------"+current);


        List<Map<String, Object>> list = userService.findMyBrithList();
        //   List<Map<String, Object>> list = userService.listMaps(query);
        return Result.ok(list);
    }

    @IsLogin
    @PostMapping("myPasswordEdit")
    public Result myPasswordEdit(
            @RequestBody JSONObject jsonObject


    ) {
        String password = jsonObject.getString("password");
        String newpassword = jsonObject.getString("newpassword");
        String repassword = jsonObject.getString("repassword");
        LoginLog loginLog = AuthConstant.getLoginLog();


        if (StringUtils.isNotEmpty(password) || StringUtils.isNotEmpty(newpassword) || StringUtils.isNotEmpty(repassword)) {
            Users users = userService.findByUserIdAndPassword(loginLog.getUserId(), password);
            if (users == null) {
                return Result.failure();
            }
            MD5 md5 = MD5.create();

            if (StringUtils.equals(newpassword, repassword)) {
                if (StringUtils.isNotEmpty(newpassword)) {

                    String s = md5.digestHex(newpassword);

                    users.setUserPassword(s);
                }

                boolean b = userService.updateById(users);
                if (b) {
                    return Result.ok();
                } else {

                    return Result.failure();
                }
            } else {
                return Result.failure();
            }

        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @PostMapping("passwordEdit")
    public Result passwordEdit(
            @RequestBody JSONObject jsonObject


    ) {
        String password = jsonObject.getString("password");
        long userId = jsonObject.getLongValue("userId");

        LoginLog loginLog = AuthConstant.getLoginLog();


        if (StringUtils.isNotEmpty(password) && userId > 0) {
            Users users = userService.findByUserId(loginLog.getUserId());
            if (users == null) {
                return Result.failure();
            }
            MD5 md5 = MD5.create();

            if (StringUtils.isNotEmpty(password)) {

                String s = md5.digestHex(password);

                users.setUserPassword(s);
            }

            boolean b = userService.updateById(users);
            if (b) {
                return Result.ok();
            } else {

                return Result.failure();
            }


        } else {
            return Result.failure();
        }

    }
    //
    @IsLogin
    @PostMapping("phoneEdit")
    public Result phoneEdit(
            @RequestBody JSONObject jsonObject


    ) {
        String phone = jsonObject.getString("phone");
        long userId = jsonObject.getLongValue("userId");

        LoginLog loginLog = AuthConstant.getLoginLog();


        if (StringUtils.isNotEmpty(phone) && userId > 0) {
            Users users = userService.findByUserId(userId);
            if (users == null) {
                return Result.failure();
            }
            users.setPhone(phone);
            boolean b = userService.updateById(users);
            if (b) {

                UsersAuthentication usersAuthentication =usersAuthenticationService.getFindByUserId(userId);
                usersAuthentication.setPhone(phone);
                if(usersAuthentication!=null){
                    usersAuthentication.setUserId(users.getId());
                    usersAuthentication.setPhone(phone);
                    usersAuthentication.setName(users.getUserName());
                    usersAuthenticationService.updateById(usersAuthentication);
                }else {
                    usersAuthenticationService.save(usersAuthentication);
                }
                return Result.ok();
            } else {

                return Result.failure();
            }


        } else {
            return Result.failure();
        }

    }
    @IsLogin
    @PostMapping("parentEdit")
    public Result parentEdit(
            @RequestBody JSONObject jsonObject


    ) {
        String phone = jsonObject.getString("phone");
        long userId = jsonObject.getLongValue("userId");

        LoginLog loginLog = AuthConstant.getLoginLog();


        if (StringUtils.isNotEmpty(phone) && userId > 0) {
            Users users = userService.findByUserId(userId);
            if (users == null) {
                return Result.failure();
            }
            Users byUserPhone = userService.findByUserPhone(phone);
            if (byUserPhone == null) {
                return Result.failure();
            }
              users.setParentUserId(byUserPhone.getId());
            boolean b = userService.updateById(users);
            if (b) {

                return Result.ok();
            } else {

                return Result.failure();
            }


        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @PostMapping("agentEdit")
    public Result agentEdit(
            @RequestBody JSONObject jsonObject


    ) {
        long agentId = jsonObject.getLongValue("agentId");
        long userId = jsonObject.getLongValue("userId");

        LoginLog loginLog = AuthConstant.getLoginLog();


        if (agentId>0 && userId > 0) {
            Users users = userService.findByUserId(userId);
            if (users == null) {
                return Result.failure();
            }
            users.setAgentId(agentId);
            boolean b = userService.updateById(users);
            if (b) {
                return Result.ok();
            } else {

                return Result.failure();
            }


        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @PostMapping("nickEdit")
    public Result nickEdit(
            @RequestBody JSONObject jsonObject


    ) {
        String nickname = jsonObject.getString("nickname");


        LoginLog loginLog = AuthConstant.getLoginLog();


        if (StringUtils.isNotEmpty(nickname) )  {
            Users users = userService.findByUserId(loginLog.getUserId());
            if (users == null) {
                return Result.failure();
            }
            users.setNickname(nickname);
            boolean b = userService.updateById(users);
            if (b) {
                return Result.ok();
            } else {

                return Result.failure();
            }


        } else {
            return Result.failure();
        }

    }




}
